package com.hanthink.system.service.impl.repair;

import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.hanthink.common.enums.DepartmentRole;
import com.hanthink.common.enums.HiddenDangerType;
import com.hanthink.common.enums.PushType;
import com.hanthink.system.service.impl.WeChatMessageServiceImpl;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.constant.Constants;
import com.hanthink.common.core.domain.entity.SysUser;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.exception.CustomException;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.repair.EquipRepairMessageVo;
import com.hanthink.system.domain.repair.RepairHelpUser;
import com.hanthink.system.domain.repair.RepairRecordFileVo;
import com.hanthink.system.domain.repair.RepairRecordInfo;
import com.hanthink.system.domain.repair.RepairRecordTime;
import com.hanthink.system.domain.repair.RequestInfo;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.repair.EquipRepairMapper;
import com.hanthink.system.mapper.repair.RepairHelpUserMapper;
import com.hanthink.system.mapper.repair.RepairRecoedMapper;
import com.hanthink.system.mapper.repair.RepairRecordTimeMapper;
import com.hanthink.system.mapper.repair.RequestMapper;
import com.hanthink.system.service.repair.IRepairRecordInfoService;

@Service
public class RepairRecordInfoServiceImpl implements IRepairRecordInfoService {

    @Autowired
    private RepairRecoedMapper repairRecoedMapper;

    @Autowired
    private RepairRecordTimeMapper repairRecordTimeMapper;

    @Autowired
    private RepairHelpUserMapper repairHelpUserMapper;

    @Autowired
    private RequestMapper requestMapper;

    @Autowired
    private EmEquipMapper emEquipMapper;

    @Autowired
    private EquipRepairMapper equipRepairMapper;

    @Autowired
    private WeChatMessageServiceImpl weChatMessageService;

    @Override
    public int insertPairRecord(List<RepairRecordInfo> list) {
        repairRecoedMapper.insertPairRecord(list);
        return 0;
    }

    @Override
    public List<RepairRecordInfo> selectWaitRepairList(Map<String, Object> params) {
        Object userName = params.get("userName");
        if (userName == null || "".equals(userName)) {
            throw new CustomException("未获取到当前登录用户信息");
        }
        Object equipName = params.get("equipName");
        if (equipName == null || "".equals(equipName)) {
            throw new CustomException("扫描设备条码有误");
        }
        // 校验设备条码在系统中是否存在
        String isExist = repairRecoedMapper.queryEquipName(String.valueOf(equipName));
        if (isExist == null) {
            throw new CustomException("设备条码[" + equipName + "]不存在,请核实");
        }
        return repairRecoedMapper.selectWaitRepairList(params);
    }

    @Override
    public List<RepairRecordInfo> selectWaitRepairListbyCode(Map<String, String> params) {
        return repairRecoedMapper.selectWaitRepairListbycode(params);
    }


    @Override
    public List<RepairRecordInfo> selectWaitRepairListsj(Map<String, Object> params) {
        Object userName = params.get("userName");
        if (userName == null || "".equals(userName)) {
            throw new CustomException("未获取到当前登录用户信息");
        }
        Object equipName = params.get("equipName");
        if (equipName == null || "".equals(equipName)) {
            throw new CustomException("扫描设备条码有误");
        }
        // 校验设备条码在系统中是否存在
        String isExist = repairRecoedMapper.queryEquipName(String.valueOf(equipName));
        if (isExist == null) {
            throw new CustomException("设备条码[" + equipName + "]不存在,请核实");
        }
        return repairRecoedMapper.selectWaitRepairListsj(params);
    }

    @Override
    public void updateRepairStatusplus(Map<String, Object> params) {
        repairRecoedMapper.updateRepairStatusplus(params);
    }

    @Override
    public int updateRepairStatus(Map<String, Object> params) {
        Object id = params.get("id");
        if (id == null || "".equals(id)) {
            throw new CustomException("获取维修单失败");
        }
        Long recordId = Long.valueOf(String.valueOf(id));
        // 校验维修单最新状态
        RepairRecordInfo repairRecordInfo = repairRecoedMapper.selectRecordById(recordId);
        if (repairRecordInfo == null) {
            throw new CustomException("获取维修单失败");
        }
        String recordStatus = repairRecordInfo.getStatus();
        if (recordStatus == null) {
            throw new CustomException("获取维修单失败");
        }
        switch (recordStatus) {
            case BusinessConstants.REPAIR_STATUS_EXECUTE:
                throw new CustomException("维修单正在执行中，禁止重新开始维修");
            case BusinessConstants.REPAIR_STATUS_FINISH:
                throw new CustomException("维修单已完成，禁止重新开始维修");
            case BusinessConstants.REPAIR_STATUS_CLOSE:
                throw new CustomException("维修单已关闭，禁止重新开始维修");
            default:
                break;
        }
        params.put("status", BusinessConstants.REPAIR_STATUS_EXECUTE);
        repairRecoedMapper.updateRepairStatus(params);

        // 插入维修执行时间记录信息
        Object repairUser = params.get("repairUser");
        Object siteKey = params.get("siteKey");
        RepairRecordTime repairRecordTime = new RepairRecordTime();
        repairRecordTime.setRecordId(recordId);// 维修记录ID
        if (repairUser != null && !"".equals(repairUser))
            repairRecordTime.setRepairUser(repairUser.toString());
        if (siteKey != null && !"".equals(siteKey))
            repairRecordTime.setSiteKey(Long.valueOf(String.valueOf(siteKey)));

        repairRecordTimeMapper.insertRecordTime(repairRecordTime);
        return 0;
    }

    @Override
    public RepairRecordInfo selectRecordById(Long id) {
        return repairRecoedMapper.selectRecordById(id);
    }

    /**
     * 根据维修单ID查询协助人信息
     *
     * @param repairHelpUser 维修协助人
     * @return
     */
    @Override
    public List<RepairHelpUser> selectHelpUser(RepairHelpUser repairHelpUser) {

        return repairHelpUserMapper.selectHelpUser(repairHelpUser);
    }

    /**
     * 根据维修单ID刪除协助人信息
     *
     * @param repairHelpUser 维修协助人
     * @return
     */
    @Override
    public void deleteHelpUserById(RepairHelpUser repairHelpUser) {

        repairHelpUserMapper.deleteHelpUserById(repairHelpUser);

    }

    /**
     * 插入维修协助人数据
     *
     * @param repairHelpUser 维修协助人
     * @return
     */
    @Override
    public void insertHelpUser(List<RepairHelpUser> list) {
        repairHelpUserMapper.insertHelpUser(list);
    }

    /**
     * 根据ID更新维修单执行人
     *
     * @param params
     * @return
     */
    @Override
    public void updateRepairUser(Map<String, Object> params) {

        // 校验单据状态
        if (params.get("id") != null) {
            Long id = (Long) params.get("id");
            RepairRecordInfo repairRecordInfo = repairRecoedMapper.selectRecordById(id);
            switch (repairRecordInfo.getStatus()) {
                case "1":
                    throw new CustomException("当前任务正在维修中，不能指派，请执行人先暂停任务");
                case "3":
                    throw new CustomException("当前任务已经完成，不能再指派");
                case "5":
                    throw new CustomException("当前任务已经关闭，不能再指派");
                default:
                    break;
            }
            Long requestId = (Long) params.get("requestId");
            // 获取报修单
            RequestInfo requestInfo = requestMapper.selectRequestVoById(requestId);
            // 更新报修单审核人
            requestInfo.setCheckUser(params.get("checkUser").toString());
            Map<String, Object> newParams = new HashMap<String, Object>();
            Long[] ids = new Long[1];
            ids[0] = requestId;
            newParams.put("ids", ids);
            newParams.put("userName", params.get("checkUser").toString());

            requestMapper.updateRequest(newParams);

            // 插入消息通知记录
            EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
            equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
            equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
            equipRepairMessageVo.setNewsType("报修指派");
            equipRepairMessageVo.setSendUser(requestInfo.getRequestUser());
            equipRepairMessageVo.setRelationId(requestId);
            equipRepairMessageVo.setSiteKey(requestInfo.getSiteKey());
            equipRepairMessageVo.setEqKey(requestInfo.getEqKey());
            equipRepairMessageVo.setNotingUser(params.get("repairUser").toString());
            // 根据设备id查询设备信息
            EmEquip emEquip = emEquipMapper.selectEmEquipById(requestInfo.getEqKey());
            equipRepairMessageVo.setNewsDesc("【报修指派】\n" + emEquip.getDesc() + "[" + emEquip.getName() + "]\n单号："
                    + repairRecordInfo.getRepairCode() + "\n审核时间：" + requestInfo.getCheckTime() + "\n审核人："
                    + params.get("checkUser").toString() + "\n请及时维修");

            equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
            repairRecoedMapper.updateRepairUser(params);
        }

    }

    @Override
    public List<RepairRecordInfo> selectWaitCheckList(Map<String, Object> params) {
        return repairRecoedMapper.selectWaitCheckList(params);
    }

    @Override
    public List<RepairRecordInfo> selectWaitCheckListRole(String site, String deptid, String username) {
        return repairRecoedMapper.selectWaitCheckListRole(site, deptid, username);
    }


    @Override
    public List<RepairRecordInfo> selectWaitCheckListRoleqx(String site, String deptid, String username) {
        return repairRecoedMapper.selectWaitCheckListRoleqx(site, deptid, username);
    }

    @Override
    public List<RepairRecordInfo> selectWaitCheckListRoleqx1(String site, String deptid, String username) {
        return repairRecoedMapper.selectWaitCheckListRoleqx1(site, deptid, username);
    }

    @Override
    public List<RepairRecordInfo> selectWaitCheckListRoleqx2(String site, String deptid, String username) {
        return repairRecoedMapper.selectWaitCheckListRoleqx2(site, deptid, username);
    }

    /**
     * 根据ID更新维修单审核状态
     *
     * @param params
     * @return
     */
    @Override
    public int updateRepairCheckStatus(Map<String, Object> params) {
        String roleName = DepartmentRole.getValue((String) params.get("deptName"));
        Object siteObj = params.get("site");
        if (ObjectUtil.isNull(siteObj)) {
            throw new CustomException(String.format("操作失败: %s", "获取操作人信息失败"));
        }
        repairRecoedMapper.updateRepairStatus(params);
        // 判定是否为重大隐患
        if (HiddenDangerType.MAJOR_HIDDEN_DANGER.getValue().equals(params.get("mergetype"))) {
            // 初审
            if (BusinessConstants.HIDDEN_DANGER_PRELIMINARY_TYPE.equals(params.get("type"))) {
                // 判断是否为审核通过
                if (BusinessConstants.REPAIR_STATUS_CLOSE_ONE.equals(params.get("status"))) {
                    // 消息推送 判定为重大隐患的 改完成
                    String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统重大隐患整改已完成，请审核。";
                    weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, PushType.PUSH_TYPE_THREE.getValue(), null);
                    // 审核不通过
                } else if (BusinessConstants.REPAIR_STATUS_NO_PASS.equals(params.get("status"))) {
                    // 判定为重大隐患的 未完成的
                    String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统重大隐患整改未完成，请确认后重新组织整改。";
                    weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, Collections.singletonList(roleName), null);
                }
                // 复审
            } else if (BusinessConstants.HIDDEN_DANGER_REEXAMINE_TYPE.equals(params.get("type"))) {
                // 判断是否为审核通过
                if (BusinessConstants.REPAIR_STATUS_CLOSE_TWO.equals(params.get("status"))) {
                    // 消息推送 判定为重大隐患的 改完成
                    String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统重大隐患整改已完成，请批示。";
                    weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, PushType.PUSH_TYPE_FOUR.getValue(), null);
                    // 审核不通过
                } else if (BusinessConstants.REPAIR_STATUS_NO_PASS.equals(params.get("status"))) {
                    // 判定为重大隐患的 未完成的
                    List<String> roles = new ArrayList<>(PushType.PUSH_TYPE_ONE.getValue());
                    roles.add(roleName);
                    String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统重大隐患整改未完成，请确认后重新组织整改。";
                    weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, roles, null);
                }
                // 终审
            } else if (BusinessConstants.HIDDEN_DANGER_FINAL_TYPE.equals(params.get("type"))) {
                List<String> roles = new ArrayList<>(PushType.PUSH_TYPE_TWO.getValue());
                roles.add(roleName);
                // 判断是否为审核通过
                if (BusinessConstants.REPAIR_STATUS_CLOSE.equals(params.get("status"))) {
                    // 消息推送 判定为重大隐患的 改完成
                    String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统重大隐患已完成。";
                    weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, roles, null);
                    // 审核不通过
                } else if (BusinessConstants.REPAIR_STATUS_NO_PASS.equals(params.get("status"))) {
                    // 判定为重大隐患的 未完成的
                    String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统重大隐患未完成，请确认后重新组织整改。";
                    weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, roles, null);
                }
            }
        } else {
            // 判断是否为审核通过
            if (BusinessConstants.REPAIR_STATUS_CLOSE.equals(params.get("status"))) {
                // 消息推送 一般隐患整改完成闭环
                String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统隐患已关闭。";
                weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, Collections.singletonList(roleName), null);
                // 审核不通过
            } else if (BusinessConstants.REPAIR_STATUS_NO_PASS.equals(params.get("status"))) {
                // 消息推送 一般隐患整改未完成的
                String pushMessage = "隐患编号:" + "【" + params.get("requestCode") + "】\n设备名称：" + params.get("equipName") + "及联动系统隐患整改未完成，请确认后重新组织整改。";
                weChatMessageService.sendMessage(Long.valueOf(params.get("site").toString()), pushMessage, Collections.singletonList(roleName), null);
            }
        }
        return 0;
    }

    /**
     * 根据报修单ID查询维修单信息
     *
     * @param params
     * @return
     */
    @Override
    public List<RepairRecordInfo> selectRepairByRequestId(RepairRecordInfo repairRecordInfo) {
        List<RepairRecordInfo> repairRecords = repairRecoedMapper.selectRepairByRequestId(repairRecordInfo);
        // 查询维修协助人
        if (repairRecords != null && repairRecords.size() > 0) {
            RepairHelpUser helpUser = new RepairHelpUser();
            helpUser.setRecordId(repairRecords.get(0).getId());
            List<RepairHelpUser> helpUsers = repairHelpUserMapper.selectHelpUser(helpUser);
            if (helpUsers.size() > 0) {
                repairRecords.get(0).setHelpUsers(helpUsers);
            }
        }
        return repairRecords;
    }

    @Override
    public List<RepairRecordInfo> selectRepairByRequestOverTime() {
        return repairRecoedMapper.selectRepairByRequestOverTime();
    }

    @Override
    public void updateRepairByRequestOverTime(Long id) {
        repairRecoedMapper.updateRepairByRequestOverTime(id);
    }

    /**
     * 根据维修单ID查询维修协助人
     *
     * @param params
     * @return
     */
    @Override
    public List<RepairHelpUser> selectHelpUserByRepairId(Long repairId) {
        // 查询维修协助人
        RepairHelpUser helpUser = new RepairHelpUser();
        helpUser.setRecordId(repairId);
        List<RepairHelpUser> helpUsers = repairHelpUserMapper.selectHelpUser(helpUser);
        return helpUsers;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRepairFile(RepairRecordInfo scv, LoginUser loginUser) {
        List<RepairRecordFileVo> resourceList = new ArrayList<RepairRecordFileVo>();
        // 保存自检信息ObjectUtils.isNotEmpty(scv)
        if (scv != null) {
            // 操作用户
            SysUser user = loginUser.getUser();

            if (scv != null) {
                // 保存自修文件信息
                RepairRecordFileVo resourceVo = null;
                if (ArrayUtils.isNotEmpty(scv.getPicList())) {
                    resourceVo = new RepairRecordFileVo();
                    String picUrl = "";
                    for (String pic : scv.getPicList()) {
                        picUrl += (pic + ";");
                    }
                    resourceVo.setFilePath(picUrl);
                    resourceVo.setRequestId(scv.getId());
                    resourceVo.setSiteKey(user.getSite());
                    resourceVo.setFileType(Constants.RESOURCE_PIC);
                    resourceList.add(resourceVo);
                }

                if (ArrayUtils.isNotEmpty(scv.getVideoList())) {
                    resourceVo = new RepairRecordFileVo();
                    String videoUrl = "";
                    for (String video : scv.getVideoList()) {
                        videoUrl += (video + ";");
                    }
                    resourceVo.setFilePath(videoUrl);
                    resourceVo.setRequestId(scv.getId());
                    resourceVo.setSiteKey(user.getSite());
                    resourceVo.setFileType(Constants.RESOURCE_VIDEO);
                    resourceList.add(resourceVo);
                }

                if (ArrayUtils.isNotEmpty(scv.getAudioList())) {
                    resourceVo = new RepairRecordFileVo();
                    String audioUrl = "";
                    for (String audio : scv.getAudioList()) {
                        audioUrl += (audio + ";");
                    }
                    resourceVo.setFilePath(audioUrl);
                    resourceVo.setRequestId(scv.getId());
                    resourceVo.setSiteKey(user.getSite());
                    resourceVo.setFileType(Constants.RESOURCE_AUDIO);
                    resourceList.add(resourceVo);
                }

                int result = repairRecoedMapper.saveRepairRecoedFileInfo(resourceList);
                return result > 0;
            }
        }
        return false;
    }

}
